<?php

class Application_Model_Auth
{

  private $_auth;

  public function __construct () {
    $this->_auth = Zend_Auth::getInstance ();
  }

  public function authorise($username, $pw,$verify,$code) {
    if (empty($username) || empty($pw))
      return false;
	if($verify==1){
		$session =new Zend_Session_Namespace('code');
		$sessionCode = $session->captcha;
		if(empty($code)||$code!=$sessionCode){
			echo json_encode(array('msg'=>'codeWrong'));
			exit;
		}
	}
	$rest = new Application_Model_Rest();
	$result = $rest->putCaptcha ($username,$pw);
	if(!empty($result)){
		$uid = $result[0]->userid;
		if($uid>0){
			$userInfo = (object) 'userInfo';
			$userInfo->id = $uid;
			$userInfo->pw = MD5($pw);
			$userInfo->username = $username;
			$userInfo->tel = $username;
			$siteIdNamespace = new Zend_Session_Namespace('siteid');
			$siteid = $siteIdNamespace->siteid;
			$userInfo->siteid = $siteid;
			$this->_auth->getStorage()->write($userInfo);
			return true;
		}
	}
    return false;
  }

  public function isLoggedIn() {
    return $this->_auth->hasIdentity();
  }
  public function logout() {
    $this->_auth->clearIdentity();
    return $this;
  }

  public function getUserId () {
    if (!$this->_auth->hasIdentity()){
		return null;
	}
	return $this->_auth->getStorage()->read()->id;
  }
  public function getSiteId(){
	 if (!$this->_auth->hasIdentity()){
		return null;
	}
	return $this->_auth->getStorage()->read()->siteid;
  }
  public function getUserName () {
    if (!$this->_auth->hasIdentity()){
		return null;
	}
	return $this->_auth->getStorage()->read()->username;
  }
  public function getTel () {
    if (!$this->_auth->hasIdentity()){
		return null;
	}
	return $this->_auth->getStorage()->read()->tel;
  }
  public function getPrivateKey() {
    if (!$this->_auth->hasIdentity()){
		return null;
	}
	return $this->_auth->getStorage()->read()->pw;
  }
  public function setSiteId($value){
		$this->_auth->getStorage()->read()->siteid=$value;
		return $this;
  }
  
}